﻿<%@ WebHandler Language="C#" Class="ContainerManagePlatHandler" %>
/*Description:批次调度平台接口
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer:Wangjh 
'create Date:20220310
'Rewriter:
'Rewrite Date:
*/
using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using Newtonsoft.Json;
using System.Collections.Generic;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Text;
using System.Collections;

public class ContainerManagePlatHandler : IHttpHandler, IRequiresSessionState
{

    CurrentUserInfo m_UserInfo;
    private LimitedCapacityBusiness m_LMObj = new LimitedCapacityBusiness();
    uLMSCommonIBusiness m_CommonObj = uMESBusinessFactory.instance.GetuLMSCommonObject();
    uLMSContainerIBusiness m_ContainerObj = uMESBusinessFactory.instance.GetuLMSContainerObject();
    uLMSCommissioningIBusiness m_Commission = uMESBusinessFactory.instance.GetuLMSCommissioning();
    YPContainerBusiness ypContainer = new YPContainerBusiness();
    RbContainerBusiness rbContainer = new RbContainerBusiness();
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "moveNon_InitProductData":
                    MoveNon_InitProductData(context);
                    break;
                case "moveNon_InitWorkflowData":
                    MoveNon_InitWorkflowData(context);
                    break;
                case "moveNon_InitStepData":
                    MoveNon_InitStepData(context);
                    break;
                case "moveNonStd":
                    MoveNonStd(context);
                    break;
                case "changeProduct":
                    ChangeProduct(context);
                    break;
                case "moveNonApsChange":
                    MoveNon_LMApsChange(context);
                    break;
                case "getReleaseReason":
                    GetReleaseReason(context);
                    break;
                case "releaseAndMoveNon":
                    ReleaseAndMoveNon(context);
                    break;
                case "CopyOldWorkflowApsData": //复制批次的旧工艺的排产数据到新工艺排产数据中 add by zhangrj 20250717
                    CopyOldWorkflowApsData(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    /// <summary>
    /// 释放和调度
    /// </summary>
    /// <param name="context"></param>
    public void ReleaseAndMoveNon(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        DataTable containers = JsonConvert.DeserializeObject<DataTable>(context.Request["containers"].ToString());
        string moveNon = context.Request["moveNon"].ToString();
        string operreason = context.Request["operReason"].ToString();

        //非标
        if (moveNon == "是")
        {
            result = _MoveNonStd(context);
            if (result.Result == false)
            {
                result.Message += ",无法调度";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
        }
        //释放
        var containerIds = "";
        foreach (DataRow dr in containers.Rows)
        {
            containerIds = string.Format("'" + dr["containerid"].ToString() + "',");
        }
        containerIds = containerIds.Trim(',');
        m_ContainerObj.OperContainerStop(containerIds, 0);
        foreach (DataRow dr in containers.Rows)
        {
            m_ContainerObj.AddDeleteContainerRecord(new Dictionary<string, string>() { 
                {"containerid",dr["containerid"].ToString ()},{"containername",dr["containername"].ToString ()},{"productid",dr["productID"].ToString ()},
                {"productname",dr["productname"].ToString ()},{"operatorid",m_UserInfo .EmployeeID },{"operreason",operreason},{"qty",dr["qty"].ToString ()},
                {"opertype","3"}
            });
        }
        if (moveNon == "是")
        {
            PopupDTO popDTO = new PopupDTO();
            popDTO.PopupKey = "moveNon";
            popDTO.Message = "";
            popDTO.ReturnData = (DataTable)result.ReturnData;
            context.Session["PopupData"] = popDTO;
        }


        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取释放原因代码
    /// </summary>
    /// <param name="context"></param>
    public void GetReleaseReason(HttpContext context)
    {
        var dt = m_CommonObj.GetHoldOrReleaseReason(0);
        context.Response.Write(JsonConvert.SerializeObject(dt));
    }
    /// <summary>
    /// 调度后---有限产能重排
    /// </summary>
    /// <param name="context"></param>
    public void MoveNon_LMApsChange(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        Dictionary<string, string> para = new Dictionary<string, string>();
        para["EmployeeID"] = m_UserInfo.EmployeeID.ToString();
        para["ApsType"] = context.Request["apstype"].ToString();
        para["PreWorkflowId"] = context.Request["preWorkflowId"].ToString();
        para["PreStepId"] = context.Request["preStepId"].ToString();
        para["PreStepSeq"] = context.Request["preStepSeq"].ToString();
        para["PreStepName"] = context.Request["preStepName"].ToString();
        para["ToApsStepId"] = context.Request["toApsStepId"].ToString();
        para["ToApsStepSeq"] = context.Request["toApsStepSeq"].ToString();
        para["ToApsStepName"] = context.Request["toApsStepName"].ToString();
        para["ToApsWorkflowId"] = context.Request["toApsWorkflowId"].ToString();
        DataTable conDt = new DataTable();
        if (!string.IsNullOrWhiteSpace(context.Request.Form["containers"].ToString()))
        {
            conDt = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["containers"].ToString());
        }
        else
        {
            result.Message = "无效参数";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }

        result = m_LMObj.MoveNon_LMApsChange(conDt, para);

        if (!result.Result)
        {
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }

        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 更改产品
    /// </summary>
    /// <param name="context"></param>
    public void ChangeProduct(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        var returnData = new DataTable();
        returnData.Columns.Add("ContainerID");

        string toProductId = context.Request["toProductId"].ToString(), toProductBaseId = context.Request["toProductBaseId"].ToString(), toProductRev = context.Request["toProductRev"].ToString(),
            toProductDesc = context.Request["toProductDesc"].ToString();
        DataTable containers = JsonConvert.DeserializeObject<DataTable>(context.Request["containers"].ToString());

        foreach (DataRow dr in containers.Rows)
        {
            if (toProductId != dr["ProductId"].ToString())
            {

                //更新container
                DatabaseHelper.ExecuteDataByEntity(new ExcuteEntity("Container", ExcuteEntity.ExcuteTypeEnum.update)
                {
                    ExcuteFileds = new List<FieldEntity>() { new FieldEntity("ProductID", toProductId, FieldEntity.FieldTypeEnum.Str) },
                    WhereFileds = new List<FieldEntity>() { new FieldEntity("ContainerID", dr["ContainerID"].ToString(), FieldEntity.FieldTypeEnum.Str) }
                });
                //更新总表
                DatabaseHelper.ExecuteDataByEntity(new ExcuteEntity("containercurrentinfo", ExcuteEntity.ExcuteTypeEnum.update)
                {
                    ExcuteFileds = new List<FieldEntity>() { new FieldEntity("ProductID", toProductId, FieldEntity.FieldTypeEnum.Str),
                    new FieldEntity("productrevision", toProductRev, FieldEntity.FieldTypeEnum.Str),new FieldEntity("productbaseid", toProductBaseId, FieldEntity.FieldTypeEnum.Str),
                    new FieldEntity("productdescription", toProductDesc, FieldEntity.FieldTypeEnum.Str)},

                    WhereFileds = new List<FieldEntity>() { new FieldEntity("ContainerID", dr["ContainerID"].ToString(), FieldEntity.FieldTypeEnum.Str) }
                });

                //调度成功后暂存一些数据
                DataRow returnRow = returnData.NewRow();
                returnRow["ContainerID"] = dr["ContainerID"].ToString();
                returnData.Rows.Add(returnRow);
            }
        }

        PopupDTO popDTO = new PopupDTO();
        popDTO.PopupKey = "productChange";
        popDTO.Message = "";
        popDTO.ReturnData = returnData;
        context.Session["PopupData"] = popDTO;

        result.Result = true;
        result.ReturnData = returnData;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 批次调度
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    uMESProcessResult _MoveNonStd(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        string strInfo = "";
        string pageType = context.Request["pageType"].ToString(), toProductId = context.Request["toProductId"].ToString(), toWorkflowName = context.Request["toWorkflowName"].ToString(),
            toWorkflowRev = context.Request["toWorkflowRev"].ToString(), toStep = context.Request["toStep"].ToString(), toStepId = context.Request["toStepId"].ToString(),
            toProductBaseId = context.Request["toProductBaseId"].ToString(), toProductRev = context.Request["toProductRev"].ToString(), toProductDesc = context.Request["toProductDesc"].ToString(),
            curWorkflowId = context.Request["curWorkflowId"].ToString(), reason = context.Request["reason"].ToString(), toWorkflowId = context.Request["toWorkflowId"].ToString(),
            toStepCode = context.Request["toStepCode"].ToString();
        int toSeq = int.Parse(context.Request["toSeq"].ToString()); DataTable containers = JsonConvert.DeserializeObject<DataTable>(context.Request["containers"].ToString());


        //返回数据 
        var returnData = new DataTable();
        returnData.Columns.Add("ContainerID");
        returnData.Columns.Add("WorkflowStepID");
        returnData.Columns["WorkflowStepID"].DefaultValue = toStepId;

        //二次验证
        foreach (DataRow dr in containers.Rows)
        {
            var rowDt = m_CommonObj.GetTableInfo("containercurrentinfo", "containerid", dr["containerid"].ToString());
            if ((rowDt.Rows[0]["isship"].ToString() == "1"))
            {
                result.Message = "选择的批次存在转工未转回";
                return result;
            }

            if ((rowDt.Rows[0]["iscommissioning"].ToString() == "1"))
            {
                result.Message = "选择的批次存在外委未转回";
                return result;
            }

            if ((rowDt.Rows[0]["splitnum"].ToString() == "1"))
            {
                result.Message = "选择的批次存在未分批完的";
                return result;
            }

            if (!string.IsNullOrWhiteSpace(rowDt.Rows[0]["WorkReportNum"].ToString()) && rowDt.Rows[0]["WorkReportNum"].ToString() != "0")
            {
                result.Message = "选择的批次存在报工不能调度";
                return result;
            }
            var tempRe = m_ContainerObj.ContainerStepIsAfterPXZY(dr["containerid"].ToString(), toWorkflowId, toSeq);
            if (tempRe.Result)
            {
                result.Message = tempRe.Message;
                return result;
            }
            if (DatabaseHelper.GetSingle(string.Format("SELECT 1 FROM containerstepworkreport2 csw WHERE csw.containerid = '{0}' AND csw.isuse = 0", dr["containerid"].ToString())) != null)
            {
                result.Message = "选择的批次存在工步报工不能调度";
                return result;
            }
            if (DatabaseHelper.GetSingle(string.Format("SELECT 1 FROM apsplandetail2 ap WHERE ap.containerid = '{0}' AND ap.status = '1'", dr["containerid"].ToString())) != null)
            {
                result.Message = "选择的批次存在排产已下发，不能调度";
                return result;
            }
        }

        var host = new ServerHostInfo();
        host.UserName = m_UserInfo.APIUserName;
        host.Password = m_UserInfo.APIPassword;
        Dictionary<string, string> shipPara = new Dictionary<string, string>();
        shipPara.Add("WorkflowID", toWorkflowId);//调到的工艺
        shipPara.Add("WorkFlowStepID", toStepId);//调到的工序
        shipPara.Add("ContainerID", "");
        shipPara["EmployeeID"] = m_UserInfo.EmployeeID.ToString();
        shipPara["FactoryID"] = m_UserInfo.FactoryID;
        shipPara["UserInfoFactory"] = m_UserInfo.FactoryID;
        shipPara["Sequence"] = toStep;
        string notMoveContainer = "";

        foreach (DataRow dr in containers.Rows)
        {
            if (toWorkflowId != curWorkflowId)//如果调到新版本工艺
            {
                var temDt = m_ContainerObj.GetStepProcessRecord(new Dictionary<string, string>()
                {
                    {"WorkFlowID",curWorkflowId},{"ContainerID",dr["ContainerID"].ToString ()}
                });
                if (temDt.Rows.Count > 0)
                {
                    notMoveContainer += dr["ContainerName"].ToString() + ",";
                    continue;
                }
            }
            //移动
            if (!m_ContainerObj.ContainerMoveNonStd(host, dr["ContainerName"].ToString(), toWorkflowName, toWorkflowRev, toStep, m_UserInfo.EmployeeName, toStepId, ref strInfo, "MoveNon"))
            {
                result.Message = strInfo;

                return result;
            }

            if (toWorkflowId != curWorkflowId)//如果调到新版本工艺
            {
                //继承当前版本的排产计划数据 add:Wangjh 20220526
                m_ContainerObj.InheritConSpecPlan(dr["ContainerID"].ToString(), curWorkflowId, toWorkflowId);
                //如果是工装工具，将虚拟序设置不加工 add by zhangrj 20230811
                string sql = string.Format(@"SELECT ws.workflowstepid FROM workflow w
                                LEFT JOIN workflowstep ws ON ws.workflowid = w.workflowid
                                LEFT JOIN factory f ON f.factoryid = w.factoryid
                                WHERE w.workflowid = '{0}' AND f.factoryname LIKE '%工装工具%' AND ws.workflowstepname LIKE '%虚拟序%'", toWorkflowId);
                DataTable dtGZStep = DatabaseHelper.Query_ReturnDatTable(sql);
                if (dtGZStep.Rows.Count > 0)
                {
                    List<Dictionary<String, String>> noshipList = new List<Dictionary<string, string>>();
                    foreach (DataRow gzStep in dtGZStep.Rows)
                    {
                        noshipList.Add(new Dictionary<String, String>(){
                                        {"ContainerId",dr["ContainerID"].ToString()},
                                        {"WorkflowStepId",gzStep["workflowstepid"].ToString()},
                                        {"CreateEmployeeId",m_UserInfo.EmployeeID}
                        });
                    }
                    if (noshipList.Count > 0)
                    {
                        ypContainer.CreateStepNoShip(noshipList);
                    }
                }
                DeleteContainerStepPlan(dr["ContainerID"].ToString());//删除手动排产数据（发送到看板的数据） add by zhangrj 20240110
            }

            //批次调度成功后，插入批次操作日志表 add zhunan 2022.6.24
            if (!string.IsNullOrWhiteSpace(reason))
            {
                m_ContainerObj.InsertOperContainerInfo(new Dictionary<string, string>() { 
                    {"ContainerName",dr["ContainerName"].ToString ()},{"ContainerID",dr["ContainerID"].ToString ()},
                    {"ProductName",dr["ProductName"].ToString ()},{"ProductID",dr["ProductID"].ToString ()},
                    {"Qty",dr["Qty"].ToString ()},{"OperatorId",m_UserInfo .EmployeeID .ToString ()},
                    {"OperReason",reason},{"OperType","4"},
                });
            }

            //调度成功后暂存一些数据
            DataRow returnRow = returnData.NewRow();
            returnRow["ContainerID"] = dr["ContainerID"].ToString();
            returnData.Rows.Add(returnRow);

            //调度到其他件号
            if (toProductId != dr["ProductId"].ToString())
            {
                //更新container
                DatabaseHelper.ExecuteDataByEntity(new ExcuteEntity("Container", ExcuteEntity.ExcuteTypeEnum.update)
                {
                    ExcuteFileds = new List<FieldEntity>() { new FieldEntity("ProductID", toProductId, FieldEntity.FieldTypeEnum.Str) },
                    WhereFileds = new List<FieldEntity>() { new FieldEntity("ContainerID", dr["ContainerID"].ToString(), FieldEntity.FieldTypeEnum.Str) }
                });
                //更新总表
                DatabaseHelper.ExecuteDataByEntity(new ExcuteEntity("containercurrentinfo", ExcuteEntity.ExcuteTypeEnum.update)
                {
                    ExcuteFileds = new List<FieldEntity>() { new FieldEntity("ProductID", toProductId, FieldEntity.FieldTypeEnum.Str),
                    new FieldEntity("productrevision", toProductRev, FieldEntity.FieldTypeEnum.Str),new FieldEntity("productbaseid", toProductBaseId, FieldEntity.FieldTypeEnum.Str),
                    new FieldEntity("productdescription", toProductDesc, FieldEntity.FieldTypeEnum.Str)},

                    WhereFileds = new List<FieldEntity>() { new FieldEntity("ContainerID", dr["ContainerID"].ToString(), FieldEntity.FieldTypeEnum.Str) }
                });
            }

            if (pageType == "2")//'装试
            {
                strInfo += "," + m_ContainerObj.DeleteOrUpdateSomeAfterDeleteOrUpdateContainer(new Dictionary<string, string>() { 
                    {"ZSType","0"},{"WorkflowID",toWorkflowId},{"ContainerID",dr["ContainerID"].ToString ()},{"TaskNo",dr["TaskNo"].ToString ()}
                });
            }
            else
            { //固定外委
                if (toStepCode == "LY05")
                {
                    m_Commission.AddFixedCommissionInfo(new Dictionary<string, string>() { 
                        {"WorkflowID",toWorkflowId},{"ContainerID",dr["ContainerID"].ToString ()},{"ContainerName",dr["ContainerName"].ToString ()},
                        {"Sequence",toSeq.ToString ()},{"WorkflowStepID",toStepId},{"FactoryID",m_UserInfo.FactoryID},
                        {"EmployeeID",m_UserInfo .EmployeeID },{"OutQty",dr["qty"].ToString()}
                    });
                }
            }
        }

        if (!string.IsNullOrWhiteSpace(notMoveContainer))
        {
            strInfo = notMoveContainer + "有派工未干完的工序";

            result.Message = strInfo;
            return result;
        }

        result.ReturnData = returnData;
        result.Result = true;
        return result;
    }

    /// <summary>
    /// 删除手动排产数据（发送到看板的数据） add by zhangrj 20240110
    /// </summary>
    /// <param name="containerID"></param>
    public void DeleteContainerStepPlan(string containerID)
    {

        string isDisSql = "SELECT 1 FROM containerstepdispatch csd WHERE csd.containerid = '{0}' AND csd.workflowstepid = '{1}' AND csd.isuse = 0";//是否存在派工
        if (m_UserInfo.Factory.Contains("热表"))
        {
            isDisSql = "SELECT 1 FROM containerstepdispatch2 csd WHERE csd.containerid = '{0}' AND csd.workflowstepid = '{1}' AND csd.isuse = 0";//是否存在工步派工
        }
        string isShipSql = @"SELECT 1 FROM apsplandetail ap 
                             LEFT JOIN apsplaninfo ai ON ai.apsplaninfoid = ap.apsplaninfoid
                             LEFT JOIN containercurrentinfo c ON c.containerid = ai.containerid
                             WHERE ai.containerid = '{0}' AND ap.workflowstepid = '{1}' AND NVL(ap.status,0) <> '0'
                             AND c.originalfactoryid <> ap.specfactoryid";//是否存在排产转工确认
        string deletePlanSql = "DELETE containerstepplan cp WHERE cp.containerstepplanid = '{0}'";//删除手动排产数据
        string sql = string.Format(@"SELECT cp.workflowstepid,cp.workflowstepname,cp.containerstepplanid FROM containerstepplan cp WHERE cp.containerid = '{0}'", containerID);//查询批次的所有手动排产数据
        DataTable dtPlan = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataRow item in dtPlan.Rows)
        {
            if (DatabaseHelper.GetSingle(string.Format(isDisSql, containerID, item["workflowstepid"].ToString())) != null)
            {
                continue;
            }
            if (DatabaseHelper.GetSingle(string.Format(isShipSql, containerID, item["workflowstepid"].ToString())) != null)
            {
                continue;
            }
            DatabaseHelper.ExecuteSql(string.Format(deletePlanSql, item["containerstepplanid"].ToString()));//删除
        }
    }

    /// <summary>
    /// 非标移动
    /// </summary>
    /// <param name="context"></param>
    public void MoveNonStd(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        result = _MoveNonStd(context);
        if (result.Result == false)
        {
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }

        PopupDTO popDTO = new PopupDTO();
        popDTO.PopupKey = "moveNon";
        popDTO.Message = "";
        popDTO.ReturnData = (DataTable)result.ReturnData;
        context.Session["PopupData"] = popDTO;

        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 工艺或产品切换弹出页面，初始化产品数据
    /// </summary>
    /// <param name="context"></param>
    public void MoveNon_InitProductData(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        string productName = "";

        var returnData = new Dictionary<string, object>();
        returnData.Add("ProductDt", null);

        if (!string.IsNullOrWhiteSpace(context.Request["productName"].ToString()))
        {
            productName = context.Request["productName"].ToString();

            var productDt = m_CommonObj.GetProductInfoByName(productName, "%");
            var productDt2 = productDt.AsEnumerable().Select(row =>
            {
                return new
                {
                    ProductID = row["ProductID"].ToString(),
                    ProductInfo = row["PRODUCTNAME"] + ":" + row["productrevision"],
                    ProductBaseID = row["ProductBaseID"].ToString(),
                    ProductRev = row["productrevision"].ToString(),
                    ProductDesc = row["description"].ToString()
                };
            });

            returnData["ProductDt"] = productDt2;
        }
        result.Result = true;
        result.ReturnData = returnData;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 工艺或产品切换弹出页面，初始化工艺数据
    /// </summary>
    /// <param name="context"></param>
    public void MoveNon_InitWorkflowData(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        string productName = "", productRev = "", curworkflowId = "", WorkFlowIsUse = "";

        var returnData = new Dictionary<string, object>();

        if (!string.IsNullOrWhiteSpace(context.Request["productName"].ToString()))
        {
            productName = context.Request["productName"].ToString();

        }
        if (!string.IsNullOrWhiteSpace(context.Request["productRev"].ToString()))
        {
            productRev = context.Request["productRev"].ToString();
        }
        if (!string.IsNullOrWhiteSpace(context.Request["curworkflowId"].ToString()))
        {
            curworkflowId = context.Request["curworkflowId"].ToString();
        }
        if (!string.IsNullOrWhiteSpace(context.Request["WorkFlowIsUse"].ToString()))
        {
            WorkFlowIsUse = context.Request["WorkFlowIsUse"].ToString();
        }

        var para = new Dictionary<String, String>();
        para.Add("ProductName", productName);
        para.Add("ProductRev", productRev);
        para.Add("FactoryID", m_UserInfo.FactoryID);
        para.Add("WorkFlowIsUse", "0");//modify by longb 20241011 只取有效

        //判定是否是热表通用工艺规程的批次
        var dt = new DataTable();
        if (DatabaseHelper.GetSingle(string.Format(@"select 1 from spec s where s.commonsubworkflow =
(select w.process_no from workflow w where w.workflowid='{0}')", curworkflowId)) == null)
        {

            //总体事业部增加字段
            if (m_UserInfo.FactoryCode == "603")
            {
                para.Add("ZS", "ZS");
            }

            dt = m_CommonObj.GetWorkflowInfoWithOtherAndSubByProductInfo(para, false, true);

            //当前批次的工艺规程及其他版本
            if (!string.IsNullOrWhiteSpace(curworkflowId) && dt.Select("WORKFLOWID='" + curworkflowId + "'").Length == 0)
            {
                string strsql = string.Format(@"select w.workflowid,WB.WORKFLOWNAME || ':' || W.WORKFLOWREVISION || '(' || W.WORKFLOWTYPE || ')' WORKFLOWNAME,W.FACTORYID,nvl(w.isuse,0) isuse 
from workflow w
LEFT JOIN WORKFLOWBASE WB ON WB.WORKFLOWBASEID=W.WORKFLOWBASEID
where w.WORKFLOWBASEID = (select WORKFLOWBASEID from workflow w where w.workflowid='{0}') ", curworkflowId);

                if (!string.IsNullOrEmpty(WorkFlowIsUse))
                {
                    strsql += " and isuse=0 ";
                }

                var dt2 = DatabaseHelper.Query_ReturnDatTable(strsql);

                foreach (DataRow dr in dt2.Rows)
                {
                    if (dt.Select("WORKFLOWID='" + dr["workflowid"].ToString() + "'").Length == 0)
                    {
                        dt.ImportRow(dr);
                    }
                }

            }

            dt.AcceptChanges();
        }
        else
        {
            dt = DatabaseHelper.Query_ReturnDatTable(string.Format(@"select w.workflowid,WB.WORKFLOWNAME || ':' || W.WORKFLOWREVISION || '(' || W.WORKFLOWTYPE || ')' WORKFLOWNAME,W.FACTORYID,w.isuse 
from workflow w
LEFT JOIN WORKFLOWBASE WB ON WB.WORKFLOWBASEID=W.WORKFLOWBASEID
where w.WORKFLOWBASEID = (select WORKFLOWBASEID from workflow w where w.workflowid='{0}') and （isuse IS NULL OR isuse=0) ", curworkflowId));

        }


        returnData.Add("WorkflowDt", dt);

        result.Result = true;
        result.ReturnData = returnData;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 工艺或产品切换弹出页面，初始化工序数据
    /// </summary>
    /// <param name="context"></param>
    public void MoveNon_InitStepData(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        string workflowId = "", containerId = "", containerName = "";

        var returnData = new Dictionary<string, object>();

        if (!string.IsNullOrWhiteSpace(context.Request["workflowId"].ToString()))
        {
            workflowId = context.Request["workflowId"].ToString();
        }
        if (!string.IsNullOrWhiteSpace(context.Request["containerId"].ToString()))
        {
            containerId = context.Request["containerId"].ToString();
        }
        if (!string.IsNullOrWhiteSpace(context.Request["containerName"].ToString()))
        {
            containerName = context.Request["containerName"].ToString();
        }

        var noComStep = m_CommonObj.GetContainerNoCompleteStep(new Dictionary<string, string>(){
            {"ContainerID",containerId },{"WorkFlowID",workflowId},{"FactoryID",m_UserInfo .FactoryID }
        });
        var stepDt = noComStep;

        if (noComStep.Rows.Count > 0)
        {
            var splitStep = m_ContainerObj.GetSplitInfoBySplitContainer(containerName);
            var curWfSplit = splitStep.Select("workflowid='" + workflowId + "'");
            if (curWfSplit.Length > 0)
            {
                var noComStepDrs = noComStep.Select("SEQUENCE>=" + curWfSplit[0]["SEQUENCE"].ToString());
                if (noComStepDrs.Length > 0)
                    stepDt = noComStep.Clone();
                else
                    stepDt = noComStepDrs.CopyToDataTable();
            }
        }

        //for (int i = 0; i < 400; i++) {
        //    stepDt.Rows.Add(i,i);
        //}


        returnData.Add("WorkflowStepDt", stepDt.AsEnumerable().Select(item =>
            new { WORKFLOWSTEPID = item["WORKFLOWSTEPID"].ToString(), WORKFLOWSTEPNAME = item["WORKFLOWSTEPNAME"].ToString(), SEQUENCE = item["SEQUENCE"].ToString(), CONTROLCODE = item["CONTROLCODE"].ToString() }));

        result.Result = true;
        result.ReturnData = returnData;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 复制批次的旧工艺的排产数据到新工艺排产数据中 add by zhangrj 20250717
    /// </summary>
    /// <param name="context"></param>
    private void CopyOldWorkflowApsData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        string oldWorkflowID = context.Request["curWorkflowId"].ToString();//旧工艺ID
        string newWorkflowID = context.Request["toWorkflowId"].ToString();//新工艺ID
        DataTable containers = JsonConvert.DeserializeObject<DataTable>(context.Request["containers"].ToString());//批次列表
        ArrayList sqlDeleList = new ArrayList();//最终执行的删除数据sql
        ArrayList sqlInsertList = new ArrayList();//最终执行的插入数据sql
        StringBuilder sqlStrb = new StringBuilder();
        List<DateTime> dtList = new List<DateTime>();
        foreach (DataRow con in containers.Rows)
        {
            if (IsExistsApsSubContainer(con["ContainerID"].ToString(), oldWorkflowID))//先判断旧工艺是否存在子卡
            {
                result.Message = string.Format("批次：{0}旧工艺存在转工子卡情况，无法继承！", con["containerName"].ToString());
                break;
            }
            if (IsExistsApsSubContainer(con["ContainerID"].ToString(), newWorkflowID))//先判断当前工艺是否存在子卡
            {
                result.Message = string.Format("批次：{0}当前工艺存在转工子卡情况，无法继承！", con["containerName"].ToString());
                break;
            }
        }
        if (!result.Result) //验证有错，则返回
        {
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        foreach (DataRow con in containers.Rows)
        {
            string containerID = con["ContainerID"].ToString();
            string apsInfoID = Guid.NewGuid().ToString();//新工艺的排产ID
            dtList.Clear();
            sqlStrb.Clear();
            sqlInsertList.Clear();
            /*
             * 得到删除新工艺的排产数据的sql
             */
            sqlDeleList = GetDeleApsSqlList(containerID, newWorkflowID);
            /*
             * 查询需要的数据
             */
            DataSet dst = GetCopyOldWorkflowQueryDatas(containerID, newWorkflowID, oldWorkflowID);
            DataTable dtOldAps = dst.Tables["dtOldAps"];//旧工艺排产数据
            DataTable dtWorkData = dst.Tables["dtWorkData"];//批次的加工数据
            /*
             * 开始继承
             */
            foreach (DataRow item in dtOldAps.Rows)//循环排产数据，进行复制
            {
                sqlStrb.Clear();
                if (dtWorkData.AsEnumerable().Where(p => p["workflowstepname"].ToString() == item["newworkflowstepname"].ToString()).Count() > 0)//如果排产工序有过加工记录，则清空执行SQL
                {
                    sqlInsertList.Clear();
                }
                if (item["status"].ToString() == "2" || item["status"].ToString() == "3") //如果是已转出或已接受，则要将旧数据置为初始状态
                {
                    sqlInsertList.Add(string.Format("UPDATE apsplandetail ap SET ap.status = '0' WHERE ap.apsplandetailid = '{0}'",item["apsplandetailid"].ToString()));
                }
                /*插入到排产明细表中*/
                sqlStrb.AppendLine(@"insert into ApsPlanDetail ad (ad.CreateDate,ad.LastChangeDate,ad.apsplandetailid,ad.apsplaninfoid,
                ad.containerid,ad.starttime,ad.endtime,ad.isuse,ad.workflowstepid,ad.workflowstepname,ad.notes,ad.workcenterid,ad.teamid,ad.resourceid,
                CreateEmployeeID,ad.SpecFactoryID,ad.Resstarttime,ad.Resendtime,ad.qty,ad.status,ad.SpecID,ad.shipreceiveempid,ad.shipreceivedate,
                ad.shiprecplanenddate,ad.shiprecplanstartdate,ad.confirmdate,ad.confirmempid) values (");
                sqlStrb.AppendFormat("{0},", "sysdate");//创建时间
                sqlStrb.AppendFormat("{0},", "sysdate");//最近更改时间
                sqlStrb.AppendFormat("'{0}',", Guid.NewGuid().ToString());//排产明细ID
                sqlStrb.AppendFormat("'{0}',", apsInfoID);//排产主表ID
                sqlStrb.AppendFormat("'{0}',", containerID);//批次ID
                sqlStrb.AppendFormat("to_date('{0}','YYYY-MM-DD HH24:MI:SS'),", item["starttime"].ToString());//排产开始时间（继承）
                sqlStrb.AppendFormat("to_date('{0}','YYYY-MM-DD HH24:MI:SS'),", item["endtime"].ToString());//排产结束时间（继承）
                sqlStrb.AppendLine("0,");//是否有效（默认有效）
                sqlStrb.AppendFormat("'{0}',", item["newworkflowstepid"].ToString());//新工序ID
                sqlStrb.AppendFormat("'{0}',", item["newworkflowstepname"].ToString());//新工序名称
                sqlStrb.AppendFormat("'{0}',", item["notes"].ToString());//备注（继承）
                sqlStrb.AppendFormat("'{0}',", item["workcenterid"].ToString());//工区ID（继承）
                sqlStrb.AppendFormat("'{0}',", item["teamid"].ToString());//班组ID（继承）
                sqlStrb.AppendFormat("'{0}',", item["resourceid"].ToString() == "'" ? "CHR(39)" : item["resourceid"].ToString());//设备ID（继承）
                sqlStrb.AppendFormat("'{0}',", m_UserInfo.EmployeeID);//创建人ID
                sqlStrb.AppendFormat("'{0}',", item["SpecFactoryID"].ToString());//工序分厂ID
                sqlStrb.AppendFormat("to_date('{0}','YYYY-MM-DD HH24:MI:SS'),", item["resstarttime"].ToString());//设备开始时间（继承）
                sqlStrb.AppendFormat("to_date('{0}','YYYY-MM-DD HH24:MI:SS'),", item["resendtime"].ToString());//设备结束时间（继承）
                sqlStrb.AppendFormat("{0},", item["qty"].ToString());//排产数量（继承）
                sqlStrb.AppendFormat("'{0}',", item["status"].ToString());//排产状态（继承）
                sqlStrb.AppendFormat("'{0}',", item["newspecid"].ToString());//新工序SpecID
                sqlStrb.AppendFormat("'{0}',", item["shipreceiveempid"].ToString());//转工接收人
                sqlStrb.AppendFormat("{0},", string.IsNullOrWhiteSpace(item["shipreceivedate"].ToString()) ? "NULL" : string.Format("to_date('{0}','YYYY-MM-DD HH24:MI:SS')", item["shipreceivedate"].ToString()));//转工接收时间
                sqlStrb.AppendFormat("{0},", string.IsNullOrWhiteSpace(item["shiprecplanenddate"].ToString()) ? "NULL" : string.Format("to_date('{0}','YYYY-MM-DD HH24:MI:SS')", item["shiprecplanenddate"].ToString()));//转工计划结束时间
                sqlStrb.AppendFormat("{0},", string.IsNullOrWhiteSpace(item["shiprecplanstartdate"].ToString()) ? "NULL" : string.Format("to_date('{0}','YYYY-MM-DD HH24:MI:SS')", item["shiprecplanstartdate"].ToString()));//转工计划开始时间
                sqlStrb.AppendFormat("{0},", string.IsNullOrWhiteSpace(item["confirmdate"].ToString()) ? "NULL" : string.Format("to_date('{0}','YYYY-MM-DD HH24:MI:SS')", item["confirmdate"].ToString()));//转工转出时间
                sqlStrb.AppendFormat("'{0}')", item["confirmempid"].ToString());//转工转出人
                sqlInsertList.Add(sqlStrb.ToString());
                dtList.Add(DateTime.Parse(item["starttime"].ToString()));
                dtList.Add(DateTime.Parse(item["endtime"].ToString()));
            }
            if (sqlInsertList.Count > 0) //必须有继承数据才执行
            {
                /*插入到主排产表中*/
                sqlStrb.Clear();
                sqlStrb.AppendLine(@"insert into ApsPlanInfo ai (ai.ApsType2,ai.apsplaninfoid,ai.apstype,ai.containerid,ai.createdate,ai.createemployeeid,ai.endtime,ai.isuse,
                ai.lastchangedate,ai.starttime,ai.workflowid) values (");
                sqlStrb.AppendLine("2,");//有限排产
                sqlStrb.AppendFormat("'{0}',", apsInfoID);//排产主表ID
                sqlStrb.AppendFormat("'{0}',", "1");//正排
                sqlStrb.AppendFormat("'{0}',", containerID);//批次ID
                sqlStrb.AppendFormat("{0},", "sysdate");//创建时间
                sqlStrb.AppendFormat("'{0}',", m_UserInfo.EmployeeID);//创建人
                sqlStrb.AppendFormat("to_date('{0}','YYYY-MM-DD HH24:MI:SS'),", dtList.Max());//排产结束日期
                sqlStrb.AppendFormat("'{0}',", "0");//是否有效
                sqlStrb.AppendFormat("{0},", "sysdate");//最近更改时间
                sqlStrb.AppendFormat("to_date('{0}','YYYY-MM-DD HH24:MI:SS'),", dtList.Min());//排产开始日期
                sqlStrb.AppendFormat("'{0}')", newWorkflowID);//新工艺ID
                sqlInsertList.Add(sqlStrb.ToString());
                DatabaseHelper.ExecuteSqlTran(sqlDeleList);
                DatabaseHelper.ExecuteSqlTran(sqlInsertList);
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "执行完成" }));
    }

    /// <summary>
    /// 判断批次对应工艺的排产是否存在转工已接受，且已经开了子卡
    /// </summary>
    /// <param name="containerID"></param>
    /// <param name="workflowID"></param>
    /// <returns></returns>
    private bool IsExistsApsSubContainer(string containerID, string workflowID)
    {
        string sql = @"SELECT 1 FROM apsplandetail ap
                        LEFT JOIN apsplaninfo ai ON ai.apsplaninfoid = ap.apsplaninfoid
                        LEFT JOIN containersubcontainer csc ON csc.containerid = ap.containerid AND csc.workflowstepid = ap.workflowstepid
                        LEFT JOIN containercurrentinfo sc ON sc.containerid = csc.subcontainerid
                        WHERE ap.containerid = '{0}' AND ai.workflowid = '{1}' AND ap.status = '3' AND sc.containerstatus != 0
                        AND NOT EXISTS(SELECT 1 FROM containersteprecord csr WHERE csr.containerid = ap.containerid AND csr.workflowstepname = ap.workflowstepname AND csr.usecompleted = 1)";
        if (DatabaseHelper.GetSingle(string.Format(sql, containerID, workflowID)) != null)
        {
            return true;
        }
        return false;
    }

    /// <summary>
    /// 获取继承工艺排产功能的查询数据
    /// </summary>
    /// <param name="containerID"></param>
    /// <param name="newWorkflowID"></param>
    /// <param name="oldWorkflowID"></param>
    /// <returns></returns>
    private DataSet GetCopyOldWorkflowQueryDatas(string containerID, string newWorkflowID, string oldWorkflowID)
    {
        DataSet ds = new DataSet();
        string sql = string.Format(@"SELECT ap.apsplandetailid,ap.starttime,ap.endtime,ap.resstarttime,ap.resendtime,ap.resourceid,ap.workcenterid,ap.teamid,ap.qty,ap.status,ap.notes,
                    ap.shipreceivedate,ap.shipreceiveempid,ap.shiprecplanenddate,ap.shiprecplanstartdate,ap.specfactoryid,ap.confirmdate,ap.confirmempid,
                    wsn.workflowstepname newworkflowstepname,wsn.workflowstepid newworkflowstepid,s.specid newspecid
                    FROM apsplandetail ap 
                    LEFT JOIN apsplaninfo ai ON ai.apsplaninfoid = ap.apsplaninfoid
                    LEFT JOIN workflowstep ws ON ws.workflowstepid = ap.workflowstepid
                    LEFT JOIN workflowstep wsn ON wsn.workflowstepname = ws.workflowstepname 
                    LEFT JOIN specbase sb ON sb.specbaseid = wsn.specbaseid
                    LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid, wsn.specid)
                    WHERE ap.containerid = '{0}' AND ai.workflowid = '{1}' AND wsn.workflowid = '{2}' AND s.factoryid = ap.specfactoryid
                    AND ai.ApsType2 = 2 AND ai.apstype = 1
                    ORDER BY ws.sequence", containerID, oldWorkflowID, newWorkflowID);
        DataTable dtOldAps = DatabaseHelper.Query_ReturnDatTable(sql);//查询出旧工艺的排产数据以及对应的新工艺工序ID
        dtOldAps.TableName = "dtOldAps";
        sql = string.Format(@"SELECT ws.workflowstepname FROM containerstepdispatch csd 
                                LEFT JOIN workflowstep ws ON ws.workflowstepid = csd.workflowstepid
                                WHERE csd.containerid = '{0}' AND csd.isuse = 0
                                UNION ALL 
                                SELECT ws.workflowstepname FROM containerstepworkreport csw
                                LEFT JOIN workflowstep ws ON ws.workflowstepid = csw.workflowstepid
                                WHERE csw.containerid = '{0}' AND csw.isuse = 0", containerID);
        DataTable dtWorkData = DatabaseHelper.Query_ReturnDatTable(sql);//查询批次的所有生产数据
        dtWorkData.TableName = "dtWorkData";
        ds.Tables.Add(dtOldAps);
        ds.Tables.Add(dtWorkData);
        return ds;
    }

    /// <summary>
    /// 删除新工艺的排产数据
    /// </summary>
    /// <param name="containerID"></param>
    /// <param name="newWorkflowID"></param>
    /// <returns></returns>
    private ArrayList GetDeleApsSqlList(string containerID, string newWorkflowID)
    {
        ArrayList sqlList = new ArrayList();
        sqlList.Add(string.Format(@"
                        DELETE FROM apsplandetailemptime apt WHERE apt.apsplandetailempid IN (
                                    SELECT ape.apsplandetailempid FROM apsplandetailemp ape
                                    WHERE ape.apsplandetailid IN (                                   
                                        SELECT ap.apsplandetailid FROM apsplandetail ap WHERE ap.apsplaninfoid IN (
                                        SELECT ai.apsplaninfoid FROM apsplaninfo ai WHERE ai.containerid = '{0}' AND ai.workflowid = '{1}' AND ai.apstype = 1 AND ai.apstype2 = 2) 
                                    ))", containerID, newWorkflowID));//删除排产人员时间明细
        sqlList.Add(string.Format(@"
                        DELETE FROM apsplandetailemp ape WHERE ape.apsplandetailid IN (                                   
                                        SELECT ap.apsplandetailid FROM apsplandetail ap WHERE ap.apsplaninfoid IN (
                                        SELECT ai.apsplaninfoid FROM apsplaninfo ai WHERE ai.containerid = '{0}' AND ai.workflowid = '{1}' AND ai.apstype = 1 AND ai.apstype2 = 2) 
                                    )", containerID, newWorkflowID));//删除排产人员
        sqlList.Add(string.Format(@"DELETE apsplandetail ap WHERE ap.apsplaninfoid IN (
                    SELECT ai.apsplaninfoid FROM apsplaninfo ai 
                    WHERE ai.containerid = '{0}' AND ai.workflowid = '{1}' AND ai.apstype = 1 AND ai.apstype2 = 2
                    )", containerID, newWorkflowID));//删除排产明细
        sqlList.Add(string.Format(@"DELETE apsplaninfo ai WHERE ai.containerid = '{0}' AND ai.workflowid = '{1}' AND ai.apstype = 1 AND ai.apstype2 = 2", containerID, newWorkflowID));//删除排产信息
        return sqlList;
    }
}